//
//  SelectProprieterViewController.m
//  LazyCat
//
//  Created by zhanshu on 15/9/8.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "SelectNearProprieterController.h"
#import "NearCollectionViewCell.h"
#import "HomeSectionHeaderTwo.h"

#import "BaseTabBarViewController.h"
#import "ShopCommonModel.h"
#import <BaiduMapAPI/BMapKit.h>//引入所有的头文件
#import "AppDelegate.h"
@interface SelectNearProprieterController ()<UICollectionViewDataSource,UICollectionViewDelegate>{
    HomeSectionHeaderTwo *_homeHeaderView;
    NSMutableArray *dataArr;
    __weak IBOutlet UIImageView *noNearMessView;//没有数据时显示的图片
}

@property (weak, nonatomic) IBOutlet UIButton *backBotton;

@property (weak, nonatomic) IBOutlet UIView *locationView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@end

@implementation SelectNearProprieterController
- (void)viewDidAppear:(BOOL)animated {
//
    CLAuthorizationStatus statu = [CLLocationManager authorizationStatus];
    //是否有网络
    if (!kNetworkNotReachability) {
        noNearMessView.hidden = YES;
        if ([CLLocationManager locationServicesEnabled]||statu == kCLAuthorizationStatusAuthorizedWhenInUse || statu == kCLAuthorizationStatusAuthorizedAlways) {
            _collectionView.hidden = NO;
            _locationView.hidden = YES;
        }else {
            _collectionView.hidden = YES;
            _locationView.hidden = NO;
        }
    }else {
        noNearMessView.hidden = YES;
        _collectionView.hidden = YES;
        _locationView.hidden = NO;
    }
    AppDelegate *appdelegate = [UIApplication sharedApplication].delegate;
    [appdelegate reLocation];

}
- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = BackColor;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(locationResult:) name:LC_Location_result object:nil];
    
    if (![AppData share].doFirst) {
        _backBotton.hidden = NO;
    }
    
    self.view.backgroundColor = BackColor;
    [_collectionView registerNib:[UINib nibWithNibName:@"NearCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"cell"];
    [_collectionView registerClass:NSClassFromString(@"UICollectionReusableView")  forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header"];
    [_collectionView registerClass:NSClassFromString(@"UICollectionReusableView")  forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header1"];
    _collectionView.backgroundColor = BackColor;
    _collectionView.alwaysBounceVertical = YES;
    
    [_backBotton setHitTestEdgeInsets:UIEdgeInsetsMake(-10, -10, -10, -10)];
    
    dataArr = [[NSMutableArray alloc] init];
    
    [_locationView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectAction:)]];
}
#pragma mark --collection  datasource  delegate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return dataArr.count;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat itemWidth = (ScreenWidth - 30)/2;
    CGFloat itemHeight = 145*itemWidth/115;
    return CGSizeMake(itemWidth, itemHeight);
    
}
//定义每个Section 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);//分别为上、左、下、右
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *Cell = @"cell";
    NearCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:Cell forIndexPath:indexPath];
    if (dataArr.count>0) {
        ShopCommonModel *model = dataArr[indexPath.row];
//        [cell.productImg setImageWithURL:[NSURL URLWithString:[model.img safeString]] placeholderImage:nil];
//        cell.productNameLable.text = model.name;
//        [cell.sendTypeBtn setTitle:model.tag forState:UIControlStateNormal];
//        cell.timeLable.text = [NSString stringWithFormat:@"营业时间:%@",model.opentime];
//        cell.distanceLable.text = model.distance;
    }
    return cell;
    
}
- (UICollectionReusableView*)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    NSString *reuseIdentifier;
    if ([kind isEqualToString: UICollectionElementKindSectionHeader ]){
        reuseIdentifier = @"Header1";
    }
    UICollectionReusableView *view =  [collectionView dequeueReusableSupplementaryViewOfKind :kind   withReuseIdentifier:reuseIdentifier   forIndexPath:indexPath];
    if (!_homeHeaderView) {
        _homeHeaderView = [[[NSBundle mainBundle] loadNibNamed:@"HomeSectionHeaderTwo" owner:self options:nil] firstObject];
        _homeHeaderView.frame = CGRectMake(0, 0, ScreenWidth, 30);
        _homeHeaderView.titleLable.text = @"周边社长";
        [view addSubview:_homeHeaderView];
    }
    return view;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(ScreenWidth, 30);
    
}

//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ShopCommonModel *model = dataArr[indexPath.row];
//    [AppData share].proprieter = model.name;
    [ShopCommonModel saveShopMess:model];

    if ([AppData share].doFirst) {
        BaseTabBarViewController *baseTab = [[BaseTabBarViewController alloc] init];
        [self.navigationController pushViewController:baseTab animated:YES];
    }else {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}

#pragma mark - 获取数据
- (void)getMess {
    NSString *url = [NSString stringWithFormat:GetStarAppMessUrl,[AppData share].lng,[AppData share].lat,[Utils md5SignStr]];
    [NTNetUtil sendRequestWithUrl:url requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
        NSDictionary *dic = networkRequest.responseData;
        NSString *r = [dic objectForKey:@"r"];
        if ([r isEqualToString:@"T"]) {
            [dataArr removeAllObjects];
            NSArray *shopArr = [dic objectForKey:@"shops"];
            for (int i =0; i <shopArr.count; i ++) {
                ShopCommonModel *model = [RMMapper objectWithClass:NSClassFromString(@"ShopCommonModel") fromDictionary:shopArr[i]];
                [dataArr addObject:model];
            }
            if (dataArr.count == 0) {
                [[MessShowView share] showWithMess:@"附近没有社长。。。"];
                _locationView.hidden = YES;
                _collectionView.hidden = YES;
                noNearMessView.hidden = NO;
            }
        }else {
            [[MessShowView share] showWithMess:[dic objectForKey:@"m"]];
        }
        [_collectionView reloadData];
    }];
}
#pragma mark - 手动选择社长
- (IBAction)selectAction:(id)sender {
    if (!kNetworkNotReachability) {
 
    }else {
        [[MessShowView share] showWithMess:@"当前网络状态不佳"];
    }
}

#pragma mark - 定位失败
- (void)locationResult:(NSNotification*)notifi {
    noNearMessView.hidden = YES;
//    [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:NO];
    BOOL doSuccess = [notifi.object boolValue];
    if (doSuccess) {
        [self getMess];
        _collectionView.hidden = NO;
        _locationView.hidden = YES;
    }else {
        _collectionView.hidden = YES;
        _locationView.hidden = NO;
        
    }
//    [AppData share].lat = 31.143885;
//    [AppData share].lng = 121.325454;
//    [self getMess];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
